package com.devicemantra.coordinate.ds.tests;
import com.devicemantra.coordinate.dataobjects.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.devicemantra.coordinate.dataobjects.CDepartmentFactory;
import com.devicemantra.coordinate.exceptions.operations.CDepartmentAlreadyExistsException;
import com.devicemantra.coordinate.exceptions.operations.CDepartmentDoesNotExistsException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@SuppressWarnings("serial")
public class AddDepartment extends HttpServlet 
{
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException 
	{
		System.out.println("Request content type is " + req.getContentType());
		resp.setContentType("text/html");
		/* Check whether a department exists with the same name */
		if(CDepartmentFactory.checkDepartmentExists(req.getParameter("dept_name")))
		{
			//resp.getOutputStream().println("[Department Check failed] <BR> ");
		}
		else
		{
			//resp.getOutputStream().println("[Department Check passed] <BR>");
		}
		
		
		CDepartment lDept = null;
		try {
			lDept = CDepartmentFactory.createNewDepartment((req.getParameter("dept_name")));
		} catch (CDepartmentAlreadyExistsException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if( lDept != null)
		{
			
			
			try {
				CDepartment lNewDept = CDepartmentFactory.getDepartment("JUSTICE");
			} catch (CDepartmentDoesNotExistsException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			PersistenceManager pm = PMF.get().getPersistenceManager();
			pm.makePersistent(lDept);
			pm.close();
			//resp.getOutputStream().print("Department Added " + lDept.getDepartmentName());
		}
		else
		{
			//resp.getOutputStream().print("Department with that name already exists ");
		}
		
		//DepartmentFactory.getAllDepartments();
		try
		{
			req.getRequestDispatcher("/modules/administration/department.jsp").forward(req,resp);
		} catch(Exception e) {}
		
		
	}
}
